package com.yunhe.sms.aspect;

import com.alibaba.fastjson.JSON;
import com.yunhe.sms.annation.Log;
import com.yunhe.sms.dao.system.LogDao;
import com.yunhe.sms.entity.system.SystemLog;
import com.yunhe.sms.servlet.Constant;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author LeiPeifeng
 * @version V1.0
 * @date 2017/11/17 0017 12:13
 * @Description: 输出日志到数据库
 */
@Component
@Aspect
public class SystemLogAspect {
    @Autowired
    private LogDao logDao;

    @Around ( "execution(public * com.yunhe.sms.service..impl.*.*(..))&&@annotation(log)" )
    public void roung(ProceedingJoinPoint joinPoint, Log log){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //从sesson中获取当前登录对象
        String userName = (String)request.getSession ().getAttribute ( Constant.SK_USER );
        int type = log.type();  //操作类型
        String value = log.value();  //操作描述
        Object[] args = joinPoint.getArgs();//获取参数
        String argsJson = JSON.toJSONString(args);  //将得到参数的JSON串
        SystemLog systemLog = new SystemLog ( value, argsJson, userName);
        try {
            joinPoint.proceed ();//执行目标方法
            systemLog.setSuccess ( true );//执行成功
        } catch (Throwable throwable) {
            systemLog.setSuccess ( false );
            throwable.printStackTrace ();
        }finally {
            logDao.save ( systemLog );
        }
    }
}
